package com.turing.post.salesmanage.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.salesmanage.util.SaleOrderActionDetail;
import com.turing.post.salesmanage.util.SaleOrderActionDetailDao;
import com.turing.post.util.Config;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;

/**
 * 
 * @author zxp
 * @Dec 23, 2012
 */
@Stateless(mappedName = "salesmanage.impl.SaleOrderActionDetailDaoImpl")
@Remote
@Local
public class SaleOrderActionDetailDaoImpl implements SaleOrderActionDetailDao {
	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	@Override
	public void insertSaleOrderActionDetail(
			SaleOrderActionDetail saleOrderActionDetail)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, saleOrderActionDetail);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SaleOrderActionDetail> getSaleOrderActionDetailList(
			String saleOrderId, Integer page) {
		int maxResult = Config.PAGE_SIZE;
		int startPosition = maxResult * page;
		String sql = "select * from SaleOrderActionDetail t where t.SaleOrderId = ?1 order by actionTime";
		Query query = _em.createNativeQuery(sql, SaleOrderActionDetail.class)
				.setFirstResult(startPosition).setMaxResults(maxResult);
		query.setParameter(1, saleOrderId);
		return query.getResultList();
	}

	@Override
	public BigInteger getSaleOrderActionDetailTotal(String saleOrderId) {
		String sql = "select nvl(count(*),0) from SaleOrderActionDetail t where t.SaleOrderId = ?1";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, saleOrderId);
		return new BigInteger(query.getSingleResult().toString());
	}
}